import React from 'react';
import { inject } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Form, Icon, Input, Button } from 'antd';
import style from './style.less';
import githubIcon from '../../static/github.svg';
const FormItem = Form.Item;

@withRouter
@inject('userStore')
class Login extends React.Component {

	async componentDidMount() {
		const { history, userStore } = this.props;	
		let arr = history.location.search.split('=');
		if(arr.length === 2 && arr[0] === '?token') {
			userStore.updateToken(arr[1]);
			const result = userStore.refeshUserInfo(arr[1]);
			if(result) history.push('/index/t1');
		}
	}

	githubLogin = async () => {
		const { userStore } = this.props;
		await userStore.githubLogin();
	}

	handleSubmit = e => {
		const { userStore, history } = this.props;
		e.preventDefault();
		this.props.form.validateFields(async (err, values) => {
			if (!err) {
				let result = await userStore.login(values);
				if(result) history.push('/index/t1');
			}
		});
	};

	render() {
		const { getFieldDecorator } = this.props.form;
		return (
			<div className={style.layout}>
				<div className={style.loginBox}>
					<Form onSubmit={this.handleSubmit} className={style.loginForm}>
						<FormItem>
							{getFieldDecorator('username', {
								rules: [{ required: true, message: 'Please input your username!' }],
							})(
								<Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="用户名" />
							)}
						</FormItem>
						<FormItem>
							{getFieldDecorator('password', {
								rules: [{ required: true, message: '请输入密码!' }],
							})(
								<Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="密码" />
							)}
						</FormItem>
						<FormItem>
							<Button type="primary" htmlType="submit" className={style.loginBtn}>
								登陆
							</Button>
						</FormItem>
						<img onClick={this.githubLogin} className={style.loginIcon} src={githubIcon} alt="github" title="github" />
					</Form>
				</div>
			</div>
		);
	}
}

const WrappedNormalLoginForm = Form.create()(Login);

export default WrappedNormalLoginForm;